#!/usr/bin/env python
from PyQt4 import QtGui
from PyQt4.QtGui import QWidget

from PyQt4 import QtCore
from PyQt4.QtCore import Qt,SIGNAL

import os
from lib.uicompile import loadUiType
from lib.profile_manager import ProfileManager

ui_path= os.path.join ( os.getcwd() , 'ui','set_options.ui')
UI_Object, Qt_Type = loadUiType(ui_path)

from os3.utils.cfgfile import CFGFile
from gui.widget import SelectAvatar


class SetOptions ( Qt_Type, UI_Object ):
	def __init__ ( self, parent = None ):
		super ( Qt_Type, self ).__init__ ( parent )
		self.__index = 0
		self.setupUi ( self )

		self.__salva = True

		#add avatar
		self.cfg_avatar = SelectAvatar ( self )
		self.avatarlayout.addWidget ( self.cfg_avatar )

		cfg_path= self._get_cfg_filename ()
		self.cfg = CFGFile ( cfg_path )
		self.cfg_properties  = [ 'name', 'dest_path', 'avatar','ipaddr' ]

		self.connect ( self.btn_path, SIGNAL ( 'clicked()' ), self._select_path );
		self.connect ( self.selIP, SIGNAL( 'currentIndexChanged(QString)' ), self.cfg_ipaddr.setText )
		self.connect ( self.btn_annulla, SIGNAL ( 'clicked()' ) , self.__annulla )



		for name  in self.cfg_properties:
			widget = getattr ( self, 'cfg_%s' % name )
			if isinstance ( widget, QtGui.QLineEdit ):
				widget.setText ( self.cfg.get ( name, '' ) )
			if isinstance ( widget, SelectAvatar ):
				widget.set_avatar ( self.cfg.get ( name, '' ) )

		self.__set_ipaddr ()


	def __set_ipaddr ( self ):
		import os3.net.utils
		import os
		ipaddr_s = os3.net.utils.get_ipaddr ()
		for ip in ipaddr_s:
			self.selIP.addItem  ( ip )


	def _select_path ( self ):
		res = QtGui.QFileDialog.getExistingDirectory ( self, 'Open file', '/home' )
		if res: self.cfg_dest_path.setText ( res )

	def __annulla ( self ):
		self.__salva = False
		self.close()

	def closeEvent  ( self, event ):

		if self.__salva :
			for name  in self.cfg_properties:
				widget = getattr( self, 'cfg_%s' % name )
				cfg_val = ''
				if isinstance( widget, QtGui.QLineEdit ):
					cfg_val = unicode ( widget.text () )
				if isinstance ( widget, SelectAvatar ):
					cfg_val = widget.path
					print "close_event" ,widget.path
				self.cfg.set ( name , cfg_val )
			self.save_cfg ()

		self.hide()
		event.ignore()



	def get_cfg ( self ):
		return self.cfg


	def save_cfg ( self ):
		cfg_path= self._get_cfg_filename ()
		fout = open ( cfg_path, "w" )
		for name in self.cfg_properties:
			fout.write ( "%s=%s\n" % ( name, self.cfg.get ( name, "" ) ) )

		fout.close ()


	def _get_cfg_filename ( self ):
		home = os.getenv ( 'USERPROFILE' ) or os.getenv ( 'HOME' )
		cfg_path = os.path.join ( home, '.woxxy.cfg' )
		return cfg_path
